import React, { useState, useRef } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Form } from 'antd';
import { Col, Row, Tag, Tooltip, notification, Popover, Space } from 'antd';
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import Uploadjs from '@/utils/aliOssUpload';
import { source, sourceSet, stage_tab } from '@/common/contact';
import SelectTagFrom from '@/components/SelectTagForm';
import GoodsSelectComponents from './components/GoodsSelectComponents';
import { phoneReg } from '@/common/regular';
import { useEffect } from 'react';
import { SearchOutlined } from '@ant-design/icons'
import { dateDisabled, cardReg } from '@/common/regular'
import PreApplition from './components/PreApplition';
import UserFieldRecordModel from '../UserFieldRecordModel';
import { filterStageInfo } from '@/utils/utils'
import moment from 'moment'
const CodeInfo = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, editMobileStatus = false } = props;
  const { location } = history;
  const { query } = location;
  const { keywordId, spiderUserId } = query;
  const { show = false, detail = {} } = visible;
  const [tagList, setTagList] = useState([])
  const [intentionDirectionList, setintentionDirectionList] = useState([])
  const [targetCourseList, setTargetCourse] = useState([])
  const [intentionCourseList, setIntentionCourseList] = useState([])
  const [intentionCoursesVisible, setIntentionCoursesVisible] = useState([])
  const [sourceType, setSourceType] = useState(null)
  const [schoolList, setSchoolList] = useState([])
  const [specialtyList, setSpecialtyList] = useState([])
  const [userFileVisible, setUserFileVisible] = useState(false)
  const [userInfoList, setUserInfoList] = useState([])
  const [tagVisible, setTagVisible] = useState(false);
  const [stageAdminStatus, setStageAdminStatus] = useState('0')
  const [checkUserList, setCheckUserList] = useState([])
  const { id, tags = '', otherMobiles = '', tagIds = '', mobile = '', stageAdminList = [], canHandlePreApplyInfoFlag = '1'
    , stage = 'potential', idCard = '', mobileEditFlag } = detail;
  const [form] = Form.useForm();
  const preRef = useRef(null);
  const { commentId, douyinUserId, accountId, accountItemId, videoId, intentionDirection = '', schoolId, specialtyId, targetCourseGoodsList = [], intentionCourseGoodsList = [],
    source: sourceData, stageAdminType = 'system' } = detail;
  useEffect(() => {
    if (!show) {
      setTagList([])
      setintentionDirectionList([])
      setIntentionCourseList([])
      setSourceType(null)
      setStageAdminStatus('system')
      setCheckUserList([])
    }
    else {
      fetchintentionDirectionList()
      fetchListSchool()
      fetchListSpecialty()
      if (id) {
        setStageAdminStatus(stageAdminType)
      }
      if (tagIds.length) {
        const listId = tagIds.split(',').reverse();
        const listName = tags.split(',')
        setTagList(listId.map((item, index) => {
          return {
            id: Number(item),
            tagName: listName[index]
          }
        }))
      }
      setSourceType(sourceData)
      if (!id) {
        dispatch({
          type: 'weCom/fetchSearchOrganizationAdmin',
          payload: {
            adminType: 'agent',
            page: 1,
            limit: 9999,
            status: ''
          },
          callback: (e) => {
            setUserInfoList(e)
          }
        })
      }

      setTargetCourse(targetCourseGoodsList)
      setIntentionCourseList(intentionCourseGoodsList)
    }
  }, [show])
  const fetchintentionDirectionList = () => {
    dispatch({
      type: 'setting/fetchIntentionCourse',
      payload: {},
      callback: (e) => {
        const { intentionCourseList } = e
        setintentionDirectionList(intentionCourseList)
      }
    });
  }
  const fetchListSchool = () => {
    dispatch({
      type: 'selectionWindow/fetchListSchool',
      payload: {
        page: '1',
        limit: '9999'
      },
      callback: (e) => {
        setSchoolList(e)
      }
    });
  }
  const fetchListSpecialty = () => {
    dispatch({
      type: 'selectionWindow/fetchListSpecialty',
      payload: {
        page: '1',
        limit: '9999'
      },
      callback: (e) => {
        setSpecialtyList(e)
      }
    });
  }
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then(async (values) => {
      const { profile, expectedRegistrationDate, userDesc, intentionDirection = [], otherMobiles = [] } = values;
      if (!tagList.length) {
        return notification.warning({
          message: '温馨提示',
          description: '请选择用户标签',
        })
      }
      const img = (await Uploadjs(profile)) || [];
      if (idCard) {
        delete values.idCard
      }
      dispatch({
        type: id ? 'video/fakeEditUserInfo' : 'video/fakeSaveUser',
        payload: {
          commentId,
          douyinUserId,
          accountId,
          accountItemId,
          keywordId,
          spiderUserId,
          videoId,
          ...values,
          otherMobiles: otherMobiles.toString(),
          userDesc: userDesc,
          tagIds: tagList.map(item => { return item.id }).toString(),
          profile: img.toString(),
          targetCourse: targetCourseList.map(item => { return item.id }).toString(),
          intentionCourses: intentionCourseList.map(item => { return item.id }).toString(),
          intentionCourseNames: intentionCourseList.map(item => { return item.goodsName }).toString(),
          expectedRegistrationDate:
            expectedRegistrationDate ? moment(expectedRegistrationDate).format('YYYY-MM-DD') : '',
          intentionDirection: intentionDirection.toString(),
          stageAdminList: stageAdminStatus === 'manual' ? preRef.current.getPre() : [],
          id,
        },
        callback: () => {
          onClose();
          handleCallback();
        },
      });
    });
  };
  const searchUserInfo = () => {
    dispatch({
      type: 'selectionWindow/fetchCheckUserInfoByName',
      payload: {
        username: form.getFieldValue('mobileSearch'),
      },
      callback: (e) => {
        setCheckUserList(e.map(item => {
          const { username, mobile } = item
          return {
            ...item,
            newUserName: mobile ? username + `(${mobile})` : username,
          }
        }))
        // form.setFieldsValue({
        //   recommendUsername: username,
        //   recommendUserId: id
        // })
      }
    })
  }
  const modalProps = {
    title: id ? `修改用户 ` : `新增用户`,
    visible: show,
    onClose,
    destroyOnClose: true,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };

  const formItems = [
    {
      label: '姓名',
      disabled: idCard,
      name: 'username',
      rightText: <Button
        onClick={
          () =>
            setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'username' } })}
        type='link'>修改记录</Button>,
      maxLength: 8
    },
    {
      label: '微信号',
      name: 'wechatId',
      rules: [{ required: false }],
      // rightText: <Button
      //   onClick={
      //     () =>
      //       setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'username' } })}
      //   type='link'>修改记录</Button>,
      // maxLength: 8
    },
    {
      label: '性别',
      name: 'gender',
      type: 'radio',
      suffix: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'gender' } })} type='link'>修改记录</Button>,
      rules: [{ required: false }],
      select: {
        1: '男',
        2: '女',
      },
    },
    {
      type: 'noForm',
      // rules: [{ required: false }],
      formItem: (
        <Row style={{ marginBottom: 24 }}>
          <Col style={{
            textAlign: 'right', paddingRight: 8, display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-end'
          }} span={6}>
            <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>标签:
          </Col>
          <Col
            style={{
              border: '1px solid #d9d9d9',
              boxSizing: 'border-box',
              height: 32,
              display: 'flex',
              alignItems: 'center',
              padding: '0 12px',
              borderRadius: 2
            }}
            onClick={() => {
              setTagVisible({
                show: true,
                detail: tagList,
              });
            }}
            className="font_hide"
            span={14}
          >
            {tagList.length === 0 && <div style={{ color: '#b2b2b2' }}>选择标签</div>}
            {
              <Tooltip
                title={tagList.map((item, index) => {
                  return item.tagName + ',';
                })}
              >
                <div className="font_hide">
                  {tagList.map((item, index) => {
                    if (index < tagList.length - 1) {
                      return item.tagName + ',';
                    }
                    return item.tagName

                  })}
                </div>
              </Tooltip>
            }

          </Col>
          <Col span={4}>
            <Button onClick={
              () =>
                setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'tagIds' } })} type='link'>修改记录</Button>
          </Col>
        </Row>
      ),
    },
    {
      label: '手机号',
      rules: [{ required: false, pattern: phoneReg, message: '请输入正确的手机号' }],
      rightText: <Button
        onClick={
          () =>
            setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'mobile' } })}
        type='link'>修改记录</Button>,
      disabled: id && !mobileEditFlag === '0' && mobile.length !== 0,
      name: 'mobile',
    },
    {
      label: '辅助号码',
      type: 'tags',
      placeholder: '该字段支持多个号码，输入单个号码按回车即为一个号码',
      open: false,
      rules: [{ required: false, type: "array", defaultField: { pattern: phoneReg, message: '请输入正确的手机号' } }],
      // onInputKeyDown: (e,) => {
      //   function isValid11DigitNumber(number) {
      //     return /^\d{11}$/.test(number);
      //   }
      //   if (e.keyCode === 13 && e.target.value && isValid11DigitNumber(e.target.value)) {
      //     let element = document.getElementById('otherMobiles')
      //     let data = form.getFieldValue('otherMobiles') ? form.getFieldValue('otherMobiles') : []
      //     form.setFieldsValue({
      //       'otherMobiles': [...data, e.target.value]
      //     })
      //     setTimeout(() => {
      //       element.value = ''
      //     }, 100)
      //   }
      // },
      name: 'otherMobiles',
    },
    {
      label: '身份证',
      rules: id ? [{ required: false, }] : [{ required: false, pattern: cardReg, message: '请输入正确的身份证号' }],
      name: 'idCard',
      maxLength: 18,
      disabled: idCard,
      rightText: <Button
        onClick={
          () =>
            setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'idCard' } })}
        type='link'>修改记录</Button>,
    },
    {
      label: '描述',
      name: 'userDesc',
      extra: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'userDesc' } })} type='link'>修改记录</Button>,
      rules: [{ required: false }],
      type: 'textArea',
    },
    {
      label: '头像',
      name: 'profile',
      type: 'upload',
      rules: [{ required: false }],
      maxFile: 1,
    },
    {
      label: '来源',
      name: 'source',
      type: 'select',
      disabled: id,
      select: id ? source : sourceSet,
      onChange: (e) => {
        setSourceType(e)
      }
    },
    {
      label: '推荐人查询',
      name: 'mobileSearch',
      placeholder: '请输入推荐人姓名',
      visible: sourceType === 'user',
      disabled: id,
      rules: [{ required: false }],
      addonAfter: <SearchOutlined onClick={() => { searchUserInfo() }}></SearchOutlined>
    },
    {
      label: '代理姓名',
      name: 'recommendAdminId',
      fieldNames: { label: 'username', value: 'id' },
      visible: sourceType === 'agent' && !id,
      type: 'select',
      select: userInfoList,
      onChange: (e, { option }) => {
        const { username, } = option
        form.setFieldsValue({
          recommendAdminName: username,
        })
      }
    },
    {
      label: '代理姓名',
      name: 'recommendAdminName',

      rules: [{ required: false }],
      hidden: true,
      visible: sourceType === 'agent' && id,
      disabled: true
    },
    {
      label: '推荐人姓名',
      name: 'recommendUsername',
      fieldNames: {
        label: 'newUserName', value: 'id',
      },
      disabled: id,
      type: 'select',
      select: checkUserList,
      visible: sourceType === 'user',
      onChange: (e, { option }) => {
        const { username, id } = option
        form.setFieldsValue({
          recommendUsername: username,
          recommendUserId: id
        })
      }
    },
    {
      label: '推荐人姓名',
      name: 'recommendUsername',
      disabled: id,
      visible: sourceType === 'oldUser',
    }, {
      label: '用户id',
      name: 'recommendUserId',
      visible: sourceType === 'user' && !id,
      hidden: true
    },
    {
      label: '意向方向',
      name: 'intentionDirection',
      onChange: (e, options) => {
        form.setFieldsValue({
          intentionDirectionName: options.map(item => {
            return item.option.courseName
          }).toString()
        })

      },
      suffix: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'intentionDirection' } })} type='link'>修改记录</Button>,
      mode: 'multiple',
      type: 'select',
      // rules: [{ required: false }],
      fieldNames: { label: 'courseName', value: 'id' },
      select: intentionDirectionList,
    },
    {
      label: '意向方向名称',
      name: 'intentionDirectionName',
      rules: [{ required: false }],
      hidden: true
    },
    {
      label: '意向度',
      name: 'intention',
      suffix: <Button
        onClick={
          () =>
            setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'intention' } })} type='link'>修改记录</Button>,
      type: 'select',
      select: {
        1: '1',
        2: '2',
        3: '3',
        4: '4',
        5: '5',
      },
    },
    // {
    //   type: 'noForm',
    //   formItem: (
    //     <GoodsSelectComponents hasSku={'0'} list={targetCourseList} setList={(e) => { setTargetCourse(e) }}></GoodsSelectComponents>
    //   ),
    // },
    {
      type: 'noForm',
      formItem: (
        <GoodsSelectComponents type='intentionCourse' hasSku={'0'} list={intentionCourseList} setList={(e) => { setIntentionCourseList(e) }}></GoodsSelectComponents>
      ),
    },
    {
      label: '预计报名时间',
      name: 'expectedRegistrationDate',
      type: 'dataPicker',
      suffix: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'expectedRegistrationDate' } })} type='link'>修改记录</Button>,
      disabledDate: dateDisabled,
      rules: [{ required: false }],
      format: 'YYYY-MM-DD',
    },
    {
      label: '学校',
      name: 'schoolId',
      onChange: (e, options) => {
        form.setFieldsValue({
          schoolName: options.option.schoolName
        })

      },
      rules: [{ required: false }],
      suffix: <Button
        onClick={
          () =>
            setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'schoolId' } })} type='link'>修改记录</Button>,
      type: 'select',
      fieldNames: { label: 'schoolName', value: 'id' },
      select: schoolList,
    },
    {
      label: '学校名称',
      name: 'schoolName',
      rules: [{ required: false }],
      hidden: true
    },
    {
      label: '专业',
      name: 'specialtyId',
      onChange: (e, options) => {
        console.log(options)
        form.setFieldsValue({
          specialtyName: options.option.specialtyName
        })

      },
      suffix: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'specialtyId' } })} type='link'>修改记录</Button>,
      type: 'select',
      rules: [{ required: false }],
      fieldNames: { label: 'specialtyName', value: 'id' },
      select: specialtyList,
    },
    {
      label: '专业名称',
      name: 'specialtyName',
      rules: [{ required: false }],
      hidden: true
    },
    {
      label: '毕业年份',
      name: 'examYear',
      rules: [{ required: false }],
      suffix: <Button onClick={
        () =>
          setUserFileVisible({ show: true, detail: { organizationUserId: id, fieldName: 'examYear' } })} type='link'>修改记录</Button>,
      type: 'select',
      select: {
        2023: 2023,
        2024: 2024,
        2025: 2025,
        2026: 2026,
        2027: 2027,
        2028: 2028,
      },
    },
    {
      label: '客户负责人指定',
      name: 'stageAdminType',
      type: 'radio',
      onChange: (e) => {
        setStageAdminStatus(e.target.value)
      },
      visible: !id,
      select: {
        system: '系统默认',
        manual: '手动指定',
        delay: '暂时不设置'
      }
    },
    {
      type: 'noForm',
      visible: !id && stageAdminStatus === 'system',
      formItem: (
        <Button type='link' onClick={() => {
          const url = history.createHref({
            pathname: '/userModule/stageAdminList',
            // 如果需要传递参数，可以在这里添加 state 或 search 属性
          });
          window.open(
            `/#/userModule/stageAdminList?onlyId=USeAJKwK`,
          );
          // history.push({
          //   pathname: ''
          // })
        }}>查看我的系统默认阶段员工 </Button>
      ),
    },
    {
      type: 'noForm',
      visible: stageAdminStatus === 'delay',
      formItem: (
        <div>请尽快设置，24小时候后系统会自动分配</div>
      ),
    },


    {
      type: 'noForm',
      visible: stageAdminStatus === 'manual',
      formItem: (
        <PreApplition
          dispatch={dispatch}
          detaultData={detail}
          ref={preRef}
          defaultList={stageAdminList.reduce((item, val) => {
            const { stage, adminInfoList = [] } = val
            return [...item, ...adminInfoList.map(o => {
              const { adminName } = o
              return {
                ...o,
                stage,
                username: adminName
              }
            })]
          }, [])} ></PreApplition>
      ),
    }
  ];

  return (
    <>
      <DrawerCondition {...modalProps}>
        <FormCondition form={form} formItems={formItems} initialValues={{
          ...detail,
          stageAdminType: 'system',
          otherMobiles: otherMobiles.length ? otherMobiles.split(',') : [], schoolId: schoolId === 0 ? '' : schoolId, specialtyId: specialtyId === 0 ? '' : specialtyId, expectedRegistrationDate: detail.expectedRegistrationDate ? moment(detail.expectedRegistrationDate, 'YYYY-MM-DD') : '', intentionDirection: intentionDirection.split(',').filter(item => {
            if (item) {
              return true
            } else {
              return false
            }
          }).map(item => { return Number(item) })
        }}></FormCondition>
      </DrawerCondition>
      <SelectTagFrom
        onSetList={setTagList}
        visible={tagVisible}
        onClose={() => setTagVisible(false)}
      ></SelectTagFrom>
      <UserFieldRecordModel
        form={form}
        visible={userFileVisible}
        onClose={() => setUserFileVisible(false)}
      ></UserFieldRecordModel>
    </>
  );
};
export default connect(({ video, loading }) => ({
  loading: loading.models.video,
}))(CodeInfo);
